
import { InjectRepository } from '@nestjs/typeorm';
import { Repository ,Not ,In,Like} from 'typeorm';
import { Injectable } from '@nestjs/common';
import { ResultData } from 'src/common/utils/result';
import { CreateCourseDto, UpdateCourseDto, QueryCourseDto } from './dto/course.dto';
import { CourseEntity } from './entities/course.entity';

@Injectable()
export class CourseService {
  constructor(
      @InjectRepository(CourseEntity)
      private readonly courseEntityRep: Repository<CourseEntity>,
  ) {}
  async create(createCourseDto: CreateCourseDto) {
    const res = await this.courseEntityRep.save(createCourseDto);
    return ResultData.ok(res);
  }

  async findAll(query :QueryCourseDto ) {
    const entity = this.courseEntityRep.createQueryBuilder('entity');
    entity.where({ delFlag: '0'});
    if(query.courseId){
      entity.andWhere("entity.courseId = :courseId", {courseId: query.courseId});
    }
    if(query.status){
      entity.andWhere("entity.status = :status", {status: query.status});
    }
    if(query.createBy){
      entity.andWhere("entity.createBy = :createBy", {createBy: query.createBy});
    }
    if(query.params?.beginTime && query.params?.endTime){
      entity.andWhere("entity.createTime BETWEEN :start AND :end", { start: query.params.beginTime, end: query.params.endTime });
    }
    if(query.courseName){
      entity.andWhere("entity.courseName LIKE :courseName", {courseName: `%${query.courseName}%`});
    }
    if (query.orderByColumn && query.isAsc) {
      const key = query.isAsc === 'ascending' ? 'ASC' : 'DESC';
      entity.orderBy(`entity.${query.orderByColumn}`, key);
    }

    // 如果没有分页参数则返回所有数据
    if (!query.pageSize || !query.pageNum) {
      const list = await entity.getMany();
      return ResultData.ok(list);
    }

    entity.skip(query.pageSize * (query.pageNum - 1)).take(query.pageSize);
    const [list, total] = await entity.getManyAndCount();

    return ResultData.ok({
      list,
      total,
    });
  }

  async findOne(id: number) {
    const res = await this.courseEntityRep.findOne({
      where: {
        delFlag: '0',
        courseId: id,
      },
    });
    return ResultData.ok(res);
  }

  async update(updateCourseDto: UpdateCourseDto) {
    const res = await this.courseEntityRep.update({  courseId: updateCourseDto.courseId }, updateCourseDto);
    return ResultData.ok({value:res.affected >= 1});
  }

  async remove(courseIds: number[]) {
    const res = await this.courseEntityRep.update(
        { courseId: In(courseIds) },
        {
          delFlag: '1',
        },
    );
    return ResultData.ok({value:res.affected >= 1});
  }
}
